package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.abc.robot01.R

import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.activity.SysMessageActivity.Companion.size
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.HousePlanDataDTO
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.Item8
import com.abc.robot01.vivemodel.HouseLayoutViewModel
import com.abc.robot01.vivemodel.HuXingShuJuViewModel
import com.abc.robot01.vivemodel.Robot
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * 户型选择
 */
class HuXingShuJuActivity : BaseActivity() {

    private val viewModel: HuXingShuJuViewModel by viewModels()

//    @Composable
//    fun DropdownMenuExample(
//        expanded: MutableState<Boolean>,
//        selected: MutableState<String>,
//        width: Dp = 374.px,
//        offsetX: Dp = 0.px,
//        offsetY: Dp = 188.px
//    ) {
//        val items: List<HouseType> by viewModel.houseTypeList.collectAsState()
//        Column(modifier = Modifier.background(Color.Blue)) {
//            Popup(
//                alignment = Alignment.TopStart,
//                offset = IntOffset(0 * 30, 0),
//                onDismissRequest = { expanded.value = false }) {
//                Card(modifier = Modifier
//                    .width(width)
//                    .offset(y = offsetY),
//                    shape = RoundedCornerShape(bottomStart=10.px, bottomEnd = 10.px),
//                    colors = CardDefaults.cardColors(containerColor = Color.White),
//                ) {
//                    LazyColumn {
//                        items(items, key = { it.id }) {
//                            Box(
//                                modifier = Modifier
////                                    .background(
////                                        color = Color.Transparent,
////                                        shape = RoundedCornerShape(5.px))
//                                    .fillMaxWidth()
//                                    .height(80.px), // 修改为 dp 或者其他单位
//                                contentAlignment = Alignment.CenterStart // 垂直和水平居中
//                            ) {
//                                BasicText(
//                                    modifier = Modifier
//                                        .offset(y = 0.dp)
//                                        .clickable {
//                                            expanded.value = false
//                                            selected.value = it.name
//                                            viewModel.selectedHouseType.value = it.code
//                                        }
//                                        .fillMaxWidth()
//                                        .height(80.px),
//                                    text = it.name,
//                                    style = TextStyle(
//                                        fontWeight = FontWeight.Normal,
//                                        textAlign = TextAlign.Center,
//                                        fontSize = 26.mysp,
//                                        color = Color.Black,
//                                    ),
//                                )
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }

//    @Composable
//    fun DropdownMenu2(
//        expanded: MutableState<Boolean>,
//        selected: MutableState<String>,
//        width: Dp = 374.px,
//        offsetX: Dp = 0.px,
//        offsetY: Dp = 0.px
//    ) {
//        val items: List<Pair<String,String>> by viewModel.designerList.collectAsState()
//        Column(modifier = Modifier.background(Color.Blue)) {
//            Popup(
//                alignment = Alignment.TopStart,
//                offset = IntOffset(0 * 30, 0),
//                onDismissRequest = { expanded.value = false }) {
//                Card(modifier = Modifier
//                    .width(width)
//                    .offset(y = offsetY),
//                    shape = RoundedCornerShape(bottomStart=10.px, bottomEnd = 10.px),
//                    colors = CardDefaults.cardColors(containerColor = Color.White),
//                ) {
//                    LazyColumn {
//                        itemsIndexed(items, key = { index, item -> item.first }) {  index, it ->
//                            val isLastItem = index == items.lastIndex
//                            Box(
//                                modifier = Modifier
////                                    .background(
////                                        color = Color.Transparent,
////                                        shape = RoundedCornerShape(5.px))
//                                    .fillMaxWidth()
//                                    .height(80.px), // 修改为 dp 或者其他单位
//                                contentAlignment = Alignment.CenterStart // 垂直和水平居中
//                            ) {
//                                BasicText(
//                                    modifier = Modifier
//                                        .clickable {
//                                            expanded.value = false
//                                            selected.value = it.second
//                                            viewModel.selectedDesigner.value = it.first
//                                        }.offset(x=30.px),
//                                    text = it.second,
//                                    style = TextStyle(
//                                        fontWeight = FontWeight.Normal,
//                                        textAlign = TextAlign.Start,
//                                        fontSize = 26.mysp,
//                                        color = Color.Black,
//                                    ),
//                                )
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }

    /**
     *  选择户型
     */
    @Composable
    fun TAB1() {
        val expanded1 = remember { viewModel.expanded1 }
        val selected1 = remember { viewModel.selected10 }

        val expanded2 = remember { viewModel.expanded2 }
        val selected2 = remember {viewModel.selected20}

        Row(verticalAlignment = Alignment.CenterVertically) {
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "户型数据名称",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            val question = remember { viewModel.name }
            CustomStyledTextField2(
                text = question, textColor = MYBLACK_Percent5, size = DpSize(200.px, 50.px)
            )
            Spacer(modifier = Modifier.width(30.px))
            BasicText(
                modifier = Modifier.offset(y = 0.dp),
                text = "备注",
                style = TextStyle(
                    fontWeight = FontWeight.Normal,
                    fontSize = 26.mysp,
                    color = MYBLACK,
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
            val remark = remember { viewModel.remark }
            CustomStyledTextField2(
                text = remark, textColor = MYBLACK_Percent5, size = DpSize(200.px, 50.px)
            )
            Spacer(modifier = Modifier.width(30.px))
                BasicText(
                    modifier = Modifier.offset(y = 0.dp),
                    text = "创建者",
                    style = TextStyle(
                        fontWeight = FontWeight.Normal,
                        fontSize = 26.mysp,
                        color = MYBLACK,
                    ),
                )

                Spacer(modifier = Modifier.width(20.px))
                Column {
                    CustomStyledTextField4(selected2,textColor = MYBLACK_Percent5) {
                        expanded2.value = expanded2.value.not()
                    }
                    if (expanded2.value) {
                        DropdownMenu2(expanded2, selected2, offsetY = (0).px)
                    }
                }
                Spacer(modifier = Modifier.width(30.px))
                MyButton01(
                    text = "查询", size = DpSize(148.px, 50.px), textColor = Color.White,
                    containerColor = MYBLUE, shape = RoundedCornerShape(25)
                ) {
                    viewModel.loadData()
                }

                Spacer(modifier = Modifier.width(30.px))
                MyButton01(
                    text = "重置",
                    size = DpSize(148.px, 50.px),
                    textColor = MYBLACK,
                    containerColor = MYBLACK_Percent10,
                    shape = RoundedCornerShape(25)
                ) {
                    viewModel.reset()
                }
        }
        Spacer(modifier = Modifier.height(30.px))
        SimpleGrid()
    }

    @Composable
    fun DropdownMenu2(
        expanded: MutableState<Boolean>,
        selected: MutableState<String>,
        width: Dp = 374.px,
        offsetX: Dp = 0.px,
        offsetY: Dp = 0.px
    ) {
        val items: List<Pair<String,String>> by viewModel.designerList.collectAsState()
        Column(modifier = Modifier.background(Color.Blue)) {
            Popup(
                alignment = Alignment.TopStart,
                offset = IntOffset(0 * 30, 0),
                onDismissRequest = { expanded.value = false }) {
                Card(modifier = Modifier
                    .width(width)
                    .offset(y = offsetY),
                    shape = RoundedCornerShape(bottomStart=10.px, bottomEnd = 10.px),
                    colors = CardDefaults.cardColors(containerColor = Color.White),
                ) {
                    LazyColumn {
                        itemsIndexed(items, key = { index, item -> item.first }) {  index, it ->
                            val isLastItem = index == items.lastIndex
                            Box(
                                modifier = Modifier
//                                    .background(
//                                        color = Color.Transparent,
//                                        shape = RoundedCornerShape(5.px))
                                    .fillMaxWidth()
                                    .height(80.px), // 修改为 dp 或者其他单位
                                contentAlignment = Alignment.CenterStart // 垂直和水平居中
                            ) {
                                BasicText(
                                    modifier = Modifier
                                        .clickable {
                                            expanded.value = false
                                            selected.value = it.second
                                            viewModel.selectedDesigner.value = it.first
                                        }.offset(x=30.px),
                                    text = it.second,
                                    style = TextStyle(
                                        fontWeight = FontWeight.Normal,
                                        textAlign = TextAlign.Start,
                                        fontSize = 26.mysp,
                                        color = Color.Black,
                                    ),
                                )
                            }
                        }
                    }
                }
            }
        }
    }


    @Composable
    fun SimpleGrid(columns: Int = 7) {
        val items: List<HousePlanDataDTO> by viewModel.questionList.collectAsState()
        // Track the currently selected item index
        val selectedIndex = remember { viewModel.selectedIndex }
        LazyVerticalGrid(
            verticalArrangement = Arrangement.spacedBy(20.px), // 可以设置垂直间隔，例如16dp
            horizontalArrangement = Arrangement.spacedBy(20.px), // 水平间隔设置为 20px
            columns = GridCells.Fixed(columns), // 2 columns in the grid
            modifier = Modifier
                .fillMaxWidth()
                .height(592.px)
                .padding(start = 0.px, end = 0.px, top = 0.px)
        ) {
            itemsIndexed(items, key = { index, item  -> item.id + item.name }) { index,item ->
                Log.e(TAG,"thumbnail:"+item.imageUrl.toString())
                ImageTextCard(item,index,selectedIndex)
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ImageTextCard(item: HousePlanDataDTO, index: Int, selectedIndex: MutableState<Int>) {
        // Background color changes based on the selected state
        val backgroundColor = if(selectedIndex.value == index) MYBLUE.copy(alpha = 0.1f) else MYBLACK_Percent5
        Box(
            modifier = Modifier
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    onClick = { // Removes ripple effect))
                        selectedIndex.value = index
//                        viewModel.selected1.value = item.renderCount > 0
                        viewModel.selected2.value = true
                        viewModel.housePlanDataId = item.id
//                        viewModel.thumbnail = item.thumbnail!!
                    })
                .background(color =backgroundColor , shape = RoundedCornerShape(14.px))
                .width(240.px)
                .height(327.px)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(0.px),
                horizontalAlignment = Alignment.Start
            ) {
                Card(
                    colors = androidx.compose.material3.CardDefaults.cardColors(
                        containerColor = MYBLACK_Percent10 // 设置背景色为红色
                    ),
                    shape = RoundedCornerShape(10.px),
                    modifier = Modifier
                        .background(Color.Transparent)
                        .width(240.px)
                        .height(240.px)
                ) {
                    GlideImage(
                        contentScale = ContentScale.Fit,
                        model = item.imageUrl,
                        contentDescription = "",
                        modifier = Modifier.fillMaxSize()
                    )
                }
                Spacer(modifier = Modifier.height(10.px))
                BasicText(
                    modifier = Modifier.offset(x=20.px),
                    maxLines = 1,
                    overflow = TextOverflow.Clip,
                    text = item.name,
                    style = TextStyle(
                        fontSize = (24 / 3.5f).sp,
                        color = Color.Black,
                        lineHeight = (24 / 3.5f).sp
                    )
                )
                Spacer(modifier = Modifier.height(5.px))

                Row(modifier = Modifier.fillMaxWidth().padding(start = 20.px , end = 20.px
                )
                ) {
                    BasicText(
                        maxLines = 1,
                        overflow = TextOverflow.Clip,
                        text = "" + item.remarks,
                        style = TextStyle(
                            fontSize = (20 / 3.5f).sp,
                            color = MYBLACK_Percent60,
                            lineHeight = (24 / 3.5f).sp
                        )
                    )
//                    Spacer(modifier = Modifier.weight(14f))
//                    BasicText(
//                        maxLines = 1,
//                        overflow = TextOverflow.Clip,
//                        text = "" + item.innerArea + "㎡",
//                        style = TextStyle(
//                            fontSize = (20 / 3.5f).sp,
//                            color = MYBLACK_Percent60,
//                            lineHeight = (24 / 3.5f).sp
//                        )
//                    )
                }
            }
            Image(
                modifier=Modifier.offset(x=189.px,y=40.px),
                painter = painterResource(id = if(selectedIndex.value == index) R.drawable.s13 else  R.drawable.s12), // 替换为你的图片资源ID
                contentDescription = null,
                contentScale = ContentScale.Crop, // 使图片填充整个背景
            )
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.reset()
    }

//    @Composable
//    fun BoxScope.TopTabs(){
//        val showLeft = remember { viewModel.showLeft }
//        val showRight = remember { viewModel.showRight }
//        val showCenter = remember { viewModel.showCenter }
//
//        if (showLeft.value) {
//            Image(
//                modifier = Modifier.align(Alignment.TopStart),
//                painter = painterResource(id = R.drawable.tab_left), // 替换为你的图片资源ID
//                contentDescription = null,
//                contentScale = ContentScale.Crop, // 使图片填充整个背景
//            )
//        }
//
//        if (showCenter.value) {
//            Image(
//                modifier = Modifier.align(Alignment.Center),
//                painter = painterResource(id = R.drawable.tab_center), // 替换为你的图片资源ID
//                contentDescription = null,
//                contentScale = ContentScale.Crop, // 使图片填充整个背景
//            )
//        }
//
//        if (showRight.value) {
//            Image(
//                modifier = Modifier.align(Alignment.BottomEnd),
//                painter = painterResource(id = R.drawable.tab_right), // 替换为你的图片资源ID
//                contentDescription = null,
//                contentScale = ContentScale.Crop, // 使图片填充整个背景
//            )
//        }
//
//        Row(
//            modifier = Modifier
//                .fillMaxSize()
//                .padding(start = 50.px)
//                .offset(0.dp, 0.dp),
//            horizontalArrangement = Arrangement.spacedBy(
//                55.px
//            ),
//            verticalAlignment = Alignment.CenterVertically
//        ) {
//            BasicText(
//                text = "选择户型",
//                style = TextStyle(
//                    fontWeight = FontWeight.Bold,
//                    fontSize = size,
//                    color = if (showLeft.value) MYBLACK else MYBLACK_Percent60,
//                ),
//                modifier = Modifier
//                    .clickable(
//                        indication = null,  // Removes the ripple effect
//                        interactionSource = remember { MutableInteractionSource() }  // Keeps track of interactions
//                    ) {
//                        showLeft.value = true;
//                        showCenter.value = false
//                        showRight.value = false;
//                    }
//            )
//            BasicText(
//                text = "导入户型",
//                style = TextStyle(
//                    fontWeight = FontWeight.Bold,
//                    fontSize = size,
//                    color = if (showCenter.value) MYBLACK else MYBLACK_Percent60,
//                ),
//                modifier = Modifier
//                    .clickable(
//                        indication = null,  // Removes the ripple effect
//                        interactionSource = remember { MutableInteractionSource() }) {
//                        showLeft.value = false;
//                        showCenter.value = true
//                        showRight.value = false;
//
//                    }
//            )
//            BasicText(
//                text = "绘制户型",
//                style = TextStyle(
//                    fontWeight = FontWeight.Bold,
//                    fontSize = size,
//                    color = if (showRight.value) MYBLACK else MYBLACK_Percent60,
//                ),
//                modifier = Modifier
//                    .clickable(
//                        indication = null,  // Removes the ripple effect
//                        interactionSource = remember { MutableInteractionSource() }) {
//                        showLeft.value = false;
//                        showCenter.value = false
//                        showRight.value = true;
//                    }
//            )
//        }
//
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val housePlansId = intent.getStringExtra("housePlansId");
        viewModel.housePlanId.value = housePlansId!!;
        viewModel.loadData()
        setContent {
//            val showLeft = remember { viewModel.showLeft }
            val selected1 by remember  { viewModel.selected1}
            val selected2 by remember  { viewModel.selected2}

            val selectedIndex by remember  { viewModel.selectedIndex}

            MaterialTheme {
                Box {
                    Image(painter = painterResource(id = R.drawable.z1), contentDescription = "")
                    Column(modifier = Modifier.padding(start = 30.px, end = 30.px, top = 30.px)) {
                        BackButton {
                        }
                        Spacer(modifier = Modifier.height(30.px))
//                        Box(
//                            modifier = Modifier
//                                .size(570.px, 90.px)
//                                .background(
//                                    Color(0x00bac3db),
//                                ),
//                        ) {
//                            // 背景图片
//                            Box(
//                                modifier = Modifier
//                                    .size(570.px, 90.px)
//                                    .background(
//                                        Color.White.copy(alpha = 0.4f), shape = RoundedCornerShape(40.px,40.px,0.px,0.px)
//                                    ),
//                            )
////                            TopTabs()
//                        }
                        SystemFragmentBackground3 {
                            Column(modifier = Modifier.padding(start = 30.px, end = 30.px)) {
                                Spacer(modifier = Modifier.height(30.px))
//                                if (showLeft.value) {
                                    TAB1()
//                                }
                            }
                        }
                    }
                    BottomBar2(
                        show = selectedIndex!=-1,
                        selected1 = selected1,
                        selected2 = selected2,
                        onClick2 =  { viewModel.reset()},
                        onClick = {
                            startActivity<RenderActivity>{
                                putExtra("housePlansDataId",viewModel.housePlanDataId)
                                putExtra("name","name is null")
                                Log.e(TAG, "designPackageId:"+ intent.getStringExtra("designPackageId"))
                                putExtra("designPackageId",intent.getStringExtra("designPackageId"))
                                putExtra("housePlansId",intent.getStringExtra("housePlansId"))
                            }
                        })
                }
            }
        }
    }

    companion object {
        val TAG = "户型数据"
    }
}

